package com.salon.modules.oss.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.salon.common.annotation.SysLog;
import com.salon.common.exception.CustomException;
import com.salon.common.http.response.PageResult;
import com.salon.modules.oss.entity.LocalFile;
import com.salon.modules.oss.service.LocalFileService;
import com.salon.modules.oss.utils.FileUtil;
import com.salon.modules.oss.vo.LocalFileQueryCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequiredArgsConstructor
@Api(tags = "本地文件")
@RequestMapping("/local/file")
public class LocalFileController {

    private final LocalFileService localFileService;

    @ApiOperation("查询文件")
    @GetMapping(value = "/list")
    public PageResult<LocalFile> queryFile(LocalFileQueryCriteria criteria, Page<Object> page) {
        return localFileService.queryAll(criteria, page);
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    public void exportFile(HttpServletResponse response, LocalFileQueryCriteria criteria) throws IOException {
        localFileService.download(localFileService.queryAll(criteria), response);
    }

    @ApiOperation("上传文件")
    @PostMapping(value = "/upload")
    public ResponseEntity<Object> createFile(@RequestParam String name, @RequestParam("file") MultipartFile file) {
        LocalFile localFile = localFileService.create(name, file);
        return new ResponseEntity<>(localFile, HttpStatus.OK);
    }

    @ApiOperation("上传图片")
    @PostMapping("/pictures")
    public ResponseEntity<LocalFile> uploadPicture(@RequestParam MultipartFile file) {
        // 判断文件是否为图片
        String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
        if (!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))) {
            throw new CustomException("只能上传图片");
        }
        LocalFile localFile = localFileService.create(null, file);
        return new ResponseEntity<>(localFile, HttpStatus.OK);
    }

    @SysLog("修改文件")
    @ApiOperation("修改文件")
    @PostMapping("/update")
    public ResponseEntity<Object> updateFile(@Validated @RequestBody LocalFile resources) {
        localFileService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @SysLog("删除文件")
    @ApiOperation("多选删除")
    @PostMapping("/delete")
    public ResponseEntity<Object> deleteFile(@RequestBody Long[] ids) {
        localFileService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}